/*
 * Copyright 2009 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vanzo.talkie;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.talkie2.R;
import com.vanzo.util.LogUtil;

import java.util.Timer;
import java.util.TimerTask;

public class TestActivity extends BaseActivity {

    private static final int TIME_OUT = 10001;
    private static final int CONNECT_SUCCESS = 100;
    private static final int CONNECT_FAIL = 101;

    private static final String DEVICE_PATH = "/dev/ttyMT0";
    private static final int DEVICE_BAUD_RATE = 9600;
    private ProgressDialog progressDialog;

    protected Application mApplication;
    private ATHelper atHelper;


    private TextView console;
    private Button correct, error;
    private ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (Application) getApplication();
        atHelper = getAtHelper();
        setContentView(R.layout.activity_serial_port);
        initView();
        connect();
    }


    private void initView() {
        scrollView = (ScrollView) findViewById(R.id.scroll_view);
        console = (TextView) findViewById(R.id.console);
        correct = (Button) findViewById(R.id.correct_button);
        error = (Button) findViewById(R.id.error_button);

        correct.setEnabled(false);
        correct.setOnClickListener(resultClickListener);
        error.setOnClickListener(resultClickListener);
    }

    private void connect() {
        atHelper.open();
        progressDialog = ProgressDialog.show(this, null, "正在初始化", false, false);
        timeOut.sendEmptyMessageDelayed(TIME_OUT, 10000);
        timer.schedule(task, 2000, 2000);
    }

    private final Timer timer = new Timer();

    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            atHelper.connect(new com.vanzo.talkie.ATHelper.Callback() {
                @Override
                public void callback(String result) {
                    LogUtil.put(TestActivity.this, "result : " + result, LogUtil.WARN);
                    if (result.contains("DMOCONNECT")) {
                        timer.cancel();
                        timeOut.removeMessages(TIME_OUT);
                        Message message = new Message();
                        message.what = CONNECT_SUCCESS;
                        message.obj = result;
                        handler.sendMessage(message);
                    }
                }
            });
        }
    };

    private Handler timeOut = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            timer.cancel();
            handler.sendEmptyMessage(CONNECT_FAIL);
        }

    };


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CONNECT_SUCCESS:
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
                    console.append((String) msg.obj);
                    TestActivity.this.setResult(RESULT_OK);
                    finish();
                    break;
                case CONNECT_FAIL:
                    Toast.makeText(TestActivity.this, "初始化失败,正在重试", Toast.LENGTH_SHORT).show();
                    TestActivity.this.setResult(RESULT_CANCELED);
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
        timeOut.removeMessages(TIME_OUT);
        timer.cancel();
        atHelper.close();
        super.onDestroy();
    }

    View.OnClickListener resultClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.correct_button:
                    TestActivity.this.setResult(RESULT_OK);
                    finish();
                    break;
                case R.id.error_button:
                    TestActivity.this.setResult(RESULT_CANCELED);
                    finish();
                    break;
            }
        }
    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }
}
